<script setup>
import { ref, watch, reactive, computed, onMounted } from 'vue'
import prop from './props'
import { createPopper } from '@popperjs/core'
import { debounce } from 'lodash-es'

defineOptions({
  name: 'LeeToolTip',
})
const props = defineProps(prop)
const visible = ref(false)
const triggerRef = ref(null)
const popperRef = ref(null)
let popperInstance = null
const popperOptions = computed(() => ({
  placement: props.placement,
  modifiers: [
    {
      name: 'offset',
      options: {
        offset: [0, 6],
      },
    },
  ],
}))
watch(
  visible,
  newValue => {
    if (newValue) {
      if (triggerRef.value && popperRef.value) {
        popperInstance = createPopper(
          triggerRef.value,
          popperRef.value,
          popperOptions.value,
        )
      } else {
        popperInstance?.destory()
      }
    }
  },
  { flush: 'post' },
)
const emit = defineEmits(['change'])
const events = reactive({})
const outerEvents = reactive({})
const openDebounce = debounce(() => {
  visible.value = true
  emit('change', visible.value)
}, props.openDelay)
const closeDebounce = debounce(() => {
  visible.value = false
  emit('change', visible.value)
}, props.openDelay)
const open = () => {
  closeDebounce.cancel()
  openDebounce()
}
const close = () => {
  openDebounce.cancel()
  closeDebounce()
}
const handleClick = () => {
  visible.value = !visible.value
  emit('change', visible.value)
}
const initEvents = () => {
  if (props.trigger === 'hover') {
    events['mouseenter'] = open
    outerEvents['mouseleave'] = close
  } else if (props.trigger === 'click') {
    events['click'] = handleClick
  }
}
defineExpose({
  show: open,
  hide: close,
})

onMounted(() => {
  if (!props.manual) {
    initEvents()
  }
})
</script>

<template>
  <div class="lee-tooltip" v-on="outerEvents">
    <div class="lee-tooltip__trigger" ref="triggerRef" v-on="events">
      <slot />
    </div>
    <div class="lee-tooltip__popper" ref="popperRef" v-show="visible">
      <slot name="content">
        {{ content }}
      </slot>
      <div id="arrow" data-popper-arrow></div>
    </div>
  </div>
</template>
